﻿using OpenCvSharp;
using System;
using System.IO;
using System.Linq;

namespace QrCodeService.Bll
{
    public class QrCodeHelper
    {
        const string _wechat_QCODE_detector_prototxt_path ="models/wechat_qrcode/detect.prototxt";
        const string _wechat_QCODE_detector_caffe_model_path = "models/wechat_qrcode/detect.caffemodel";
        const string _wechat_QCODE_super_resolution_prototxt_path = "models/wechat_qrcode/sr.prototxt";
        const string _wechat_QCODE_super_resolution_caffe_model_path = "models/wechat_qrcode/sr.caffemodel";
        /// <summary>
        /// 使用wechat_qrcode模型识别二维码
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>二维码内容</returns>
        public string Detect1(byte[] file)
        {
            using var wechatQrcode = OpenCvSharp.WeChatQRCode.Create(
               Path.Combine(AppContext.BaseDirectory, _wechat_QCODE_detector_prototxt_path), Path.Combine(AppContext.BaseDirectory, _wechat_QCODE_detector_caffe_model_path),
                                                        Path.Combine(AppContext.BaseDirectory, _wechat_QCODE_super_resolution_prototxt_path), Path.Combine(AppContext.BaseDirectory, _wechat_QCODE_super_resolution_caffe_model_path));
            using var src = Cv2.ImDecode(file, ImreadModes.Color);
            wechatQrcode.DetectAndDecode(src, out var rects, out var texts);
            return texts.FirstOrDefault();
        }
        /// <summary>
        /// 使用opencv识别二维码
        /// </summary>
        /// <param name="file">The file.</param>
        /// <returns>二维码内容</returns>
        public string Detect2(byte[] file)
        {
            using var wechatQrcode2 = new OpenCvSharp.QRCodeDetector();
            using var src = Cv2.ImDecode(file, ImreadModes.Color);
            return wechatQrcode2.DetectAndDecode(src, out Point2f[] points);
        }
    }
}
